#include "cppinc/ads8686s.h"
#include "cppinc/log.h"
#include "bsp.h"

void DrvAds8686s::Init()
{
    uint8_t adcConfig[] = { 0x70, 0x12, 0x70,0x00, 0x00, 0xff,0xff,0x00 };
    BspGpioSet(m_io.cs, GPIO_CLR);
    BspDatabusWriteRead(m_dataBus, adcConfig, NULL, sizeof(adcConfig));
    BspGpioSet(m_io.cs, GPIO_SET);
    ReadState();
}

/* 通过读取芯片ID判定对应ADC是否在位 */
void DrvAds8686s::ReadState()
{
    uint8_t readIdReg[] = { 0x49, 0xff };
    uint8_t IDReg[2] = { 0 };
    BspGpioSet(m_io.cs, GPIO_CLR);
    BspDatabusWriteRead(m_dataBus, readIdReg, IDReg, sizeof(readIdReg));
    BspGpioSet(m_io.cs, GPIO_SET);

    LOG("ADS ID[%02x] (ADS8686s ID should be 0x8b)", IDReg[1]);
    m_sta = IDReg[1] == ADC8686S_ID_VALID ? ADC_CHIP_RDY : ADC_CHIP_WRONG_ID;
}

uint8_t DrvAds8686s::ReadChnl(uint8_t ch, int32_t& adcVal)
{
    // trigger conver start
    BspGpioSet(m_io.start, GPIO_SET);
    m_delayus(10);
    BspGpioSet(m_io.start, GPIO_CLR);

    // wait for conver done
    int32_t timeoutUs = 1000;
    while (timeoutUs-- > 0 && BspGpioGet(m_io.rdy) == GPIO_SET) {
        m_delayus(1);
    }

    // read back data
    uint8_t txbuf[5] = { 0x30, 0, 0, 0, 0};
    uint8_t rxbuf[5] = { 0 };
    BspGpioSet(m_io.cs, GPIO_CLR);
    BspDatabusWriteRead(m_dataBus, txbuf, rxbuf, sizeof (txbuf));
    BspGpioSet(m_io.cs, GPIO_SET);

    // return data
    uint32_t regVal = (rxbuf[2] << 24) | (rxbuf[3] << 16) | (rxbuf[4] << 8);
    adcVal = (int32_t)regVal / (1 << 8);
    return rxbuf[1];
}
